package com.epam.player.desktop.logic;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.epam.player.desktop.common.Constant;
import com.epam.player.desktop.exceptions.PropertiesLoadException;

public class PropertiesLoader {

	public Map<String, String> getProperties() throws PropertiesLoadException {
		Properties properties = loadProperties(Constant.pathConfigFile);
		return transofmProperties(properties);
	}

	public void saveProperties(Map<String, String> data) {
		Properties prop = new Properties();
		prop.putAll(data);
		OutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(Constant.pathConfigFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		try {
			prop.store(outputStream, null);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private Map<String, String> transofmProperties(Properties properties)
			throws PropertiesLoadException {
		Map<String, String> data = new HashMap<String, String>();
		data.put(Constant.EMAIL, properties.getProperty(Constant.EMAIL));
		data.put(Constant.PASS, properties.getProperty(Constant.PASS));
		return data;

	}

	private Properties loadProperties(String pathFile)
			throws PropertiesLoadException {
		Properties prop = new Properties();
		InputStream inputStream;
		try {
			inputStream = new FileInputStream(pathFile);
		} catch (FileNotFoundException e) {
			throw new PropertiesLoadException(e);
		}
		try {
			prop.load(inputStream);
		} catch (IOException e) {
			throw new PropertiesLoadException(e);
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return prop;

	}
}
